package cn.smdq.ch.auth.center.service;

import cn.smdq.ch.common.constant.CommonConstants;
import cn.smdq.ch.common.constant.SecurityConstants;
import cn.smdq.ch.common.vo.RoleVO;
import cn.smdq.ch.common.vo.UserVO;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.util.CollectionUtils.isEmpty;

/**
 * @Description TODO
 * @Author shuimodanqing
 * @Date 2019/1/21  1:05 PM
 */
@Data
public class UserDetailImpl implements UserDetails {

    private static final long serialVersionUID = 1L;

    private Integer userId;

    private String username;

    private String password;

    private String status;

    private List<RoleVO> roleList;

    public UserDetailImpl(UserVO userVO) {
        this.userId = userVO.getId();
        this.username = userVO.getUsername();
        this.password = userVO.getPassword();
        this.status = userVO.getDelFlag();
        this.roleList = userVO.getRoleList();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(SecurityConstants.BASE_ROLE));
        authorityList = !isEmpty(this.roleList) ? this.roleList.stream().map(role -> new SimpleGrantedAuthority(role.getRoleCode())).collect(Collectors.toList()) : authorityList;
        return authorityList;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !StringUtils.equals(CommonConstants.STATUS_LOCK, this.status);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return !StringUtils.equals(CommonConstants.STATUS_NORMAL, this.status);
    }
}
